package com.ruoyi.washer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.washer.common.PaymentDivideServiceImpl;
import com.ruoyi.washer.common.PaymentRefundServiceImpl;
import com.ruoyi.washer.config.WeChatConfig;
import com.ruoyi.washer.controller.WeChatController01;
import com.ruoyi.washer.domain.*;
import com.ruoyi.washer.mapper.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.washer.service.IXwPurchaseOrderService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 购买记录Service业务层处理
 *
 * @author hawking
 * @date 2023-12-15
 */
@Service
public class XwPurchaseOrderServiceImpl implements IXwPurchaseOrderService
{
    @Autowired
    private XwPurchaseOrderMapper xwPurchaseOrderMapper;
    @Autowired
    private XwDeviceMapper xwDeviceMapper;

    @Autowired
    private XwAgentMapper xwAgentMapper;

    @Autowired
    private XwEnduserMapper xwEnduserMapper;

    @Autowired
    private PaymentRefundServiceImpl paymentRefundServiceImpl;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private PaymentDivideServiceImpl paymentDivideServiceImpl;

    @Autowired
    private XwDivideAccountsMapper xwDivideAccountsMapper;

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private WeChatConfig weChatConfig;

    private static final Logger logger = LoggerFactory.getLogger(XwPurchaseOrderServiceImpl.class);
    /**
     * 查询购买记录
     *
     * @param orderNo 购买记录主键
     * @return 购买记录
     */
    @Override
    public XwPurchaseOrder selectXwPurchaseOrderByOrderNo(Long orderNo)
    {
        return xwPurchaseOrderMapper.selectXwPurchaseOrderByOrderNo(orderNo);
    }

    /**
     * 查询购买记录列表
     *
     * @param xwPurchaseOrder 购买记录
     * @return 购买记录
     */
    @Override
    public List<XwPurchaseOrder> selectXwPurchaseOrderList(XwPurchaseOrder xwPurchaseOrder)
    {
        return xwPurchaseOrderMapper.selectXwPurchaseOrderList(xwPurchaseOrder);
    }

    /**
     * 新增购买记录
     *
     * @param xwPurchaseOrder 购买记录
     * @return 结果
     */
    @Override
    public int insertXwPurchaseOrder(XwPurchaseOrder xwPurchaseOrder)
    {
        return xwPurchaseOrderMapper.insertXwPurchaseOrder(xwPurchaseOrder);
    }

    /**
     * 修改购买记录
     *
     * @param xwPurchaseOrder 购买记录
     * @return 结果
     */
    @Override
    public int updateXwPurchaseOrder(XwPurchaseOrder xwPurchaseOrder)
    {
        return xwPurchaseOrderMapper.updateXwPurchaseOrder(xwPurchaseOrder);
    }

    /**
     * 批量删除购买记录
     *
     * @param orderNos 需要删除的购买记录主键
     * @return 结果
     */
    @Override
    public int deleteXwPurchaseOrderByOrderNos(Long[] orderNos)
    {
        return xwPurchaseOrderMapper.deleteXwPurchaseOrderByOrderNos(orderNos);
    }

    /**
     * 删除购买记录信息
     *
     * @param orderNo 购买记录主键
     * @return 结果
     */
    @Override
    public int deleteXwPurchaseOrderByOrderNo(Long orderNo)
    {
        return xwPurchaseOrderMapper.deleteXwPurchaseOrderByOrderNo(orderNo);
    }

    public List<XwPurchaseOrder> getClientOrders(String openId){
        return xwPurchaseOrderMapper.getClientOrdersByOpenId(openId);
    }


    @Transactional
    public int dealGiveBackBall(String washballSn,String deviceSn,String openId)throws Exception{
        XwPurchaseOrder xwPurchaseOrder=xwPurchaseOrderMapper.getClientOrdersByWashballSn(washballSn);
        if(xwPurchaseOrder==null){//没有需要处理的订单
            return 1;
        }
        String deviceSn1=xwPurchaseOrder.getDeviceSn();
        XwDevice xwDevice1=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn1);//租借的终端设备
        String openId1=xwDevice1.getEnduserOpenId();
        XwDevice xwDevice2=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);//归还终端设备
        String openId2=xwDevice2.getEnduserOpenId();
        if(openId1!=null&&openId2!=null&&!openId1.equals(openId2)){//不是同一个终端的设备
            return 2;
        }
        if(openId1!=null&&!openId1.equals("")&&(openId2==null||openId2.equals(""))){
            return 2;
        }
        Date startDate=xwPurchaseOrder.getRentStartTime();
        Date endDate=new Date();
        // 计算日期差异
        boolean isCancel = false;
        int amount = 0;
        long minutesDifference = (endDate.getTime() - startDate.getTime()) / (60 * 1000);//相差的分钟数
        if(minutesDifference<=10){//小于10分钟全额退款
            BigDecimal payAmountReal=xwPurchaseOrder.getPayAmountReal();
            xwPurchaseOrder.setUpdatedTime(endDate);
            xwPurchaseOrder.setFinishState("Y");
            xwPurchaseOrder.setRefundAmount(payAmountReal);
            xwPurchaseOrder.setRefundState("2");
            xwPurchaseOrder.setRentEndTime(endDate);
            xwPurchaseOrder.setIsCancel("1");
            xwPurchaseOrderMapper.updateXwPurchaseOrder(xwPurchaseOrder);
            if("2".equals(xwPurchaseOrder.getPayType())) {
                paymentRefundServiceImpl.createRefundOrder(xwPurchaseOrder.getOutTradeNo(),
                        payAmountReal.intValue(),payAmountReal.intValue());
            }
            isCancel = true;
        }else{
            int refund=0;
            BigDecimal payAmountReal=xwPurchaseOrder.getPayAmountReal();//支付金额
            BigDecimal perhourPrice=xwPurchaseOrder.getPerhourPrice();//每个小时消费金额
            System.out.println("perhourPrice=="+perhourPrice);
            SysConfig sysConfig=sysConfigMapper.checkConfigKeyUniqueNew("xw_top_money");
            String top=sysConfig.getConfigValue();//每天封顶金额
            BigDecimal topMoneyFen=new BigDecimal(top).multiply(new BigDecimal(100));//每天封顶金额转成分
            List<LocalDate> dateRange=getDateList(startDate,endDate);
            logger.error("top=="+top);
            logger.error("dateRange.size()=="+dateRange.size());
            logger.error("topMoneyFen:"+topMoneyFen.intValue());
            if(dateRange.size()==1){
                long hoursDifference = (minutesDifference + 59) / 60; // 考虑时区差异
                logger.error("dateRange.size()==1,hoursDifference:"+hoursDifference);
                logger.error("payAmountReal:"+payAmountReal.intValue());
                BigDecimal money01=perhourPrice.multiply(new BigDecimal(""+hoursDifference));//小时剩于单价。元
                BigDecimal rentMoneyFen=money01.multiply(new BigDecimal("100"));
                logger.error("rentMoneyFen:"+rentMoneyFen.intValue());
                if(rentMoneyFen.compareTo(topMoneyFen)>0){//是否封顶
                    logger.error("01:");
                    refund=payAmountReal.subtract(topMoneyFen).intValue();
                    amount = topMoneyFen.intValue();
                }else{
                    refund=payAmountReal.subtract(rentMoneyFen).intValue();
                    logger.error("02:");
                    amount = rentMoneyFen.intValue();
                }
                logger.error("dateRange.size()==1,refund:"+refund);
            }else if(dateRange.size()>1){
                int consume=0;//总的消费金额
                //前面第一天的消费金额统计
                String str1=dateRange.get(0).toString()+" 23:59:59";
                String format = "yyyy-MM-dd HH:mm:ss"; // 这是字符串的日期时间格式
                SimpleDateFormat sdf = new SimpleDateFormat(format);
                Date firstDateEnd = sdf.parse(str1);//
                long minutes1 = (firstDateEnd.getTime() - startDate.getTime()) / (60 * 1000);
                long hoursDifference1 = (minutes1 + 59) / 60; // 考虑时区差异
                BigDecimal money01=perhourPrice.multiply(new BigDecimal(""+hoursDifference1));//小时剩于单价。元
                BigDecimal rentMoneyFen01=money01.multiply(new BigDecimal("100"));//转成分
                if(rentMoneyFen01.compareTo(topMoneyFen)>0){//是否封顶
                    consume=consume+topMoneyFen.intValue();
                }else{
                    consume=consume+rentMoneyFen01.intValue();
                }
                logger.error("consume1:"+consume);
                //中间日期
                if(dateRange.size()-2>0){
                    int dataCount=dateRange.size()-2;
                    consume=consume+perhourPrice.multiply(new BigDecimal("100")).multiply(new BigDecimal(""+dataCount)).intValue();
                }
                logger.error("consume2:"+consume);
                //最后一天的计算
                str1=dateRange.get(dateRange.size()-1).toString()+" 00:00:00";
                Date endDateStart = sdf.parse(str1);//
                long minutes02 = (endDate.getTime() - endDateStart.getTime()) / (60 * 1000);
                long hoursDifference02 = (minutes02 + 59) / 60; // 考虑时区差异
                BigDecimal money02=perhourPrice.multiply(new BigDecimal(""+hoursDifference02));//小时剩于单价。元
                BigDecimal rentMoneyFen02=money02.multiply(new BigDecimal("100"));//转成分
                if(rentMoneyFen02.compareTo(topMoneyFen)>0){//是否封顶
                    consume=consume+topMoneyFen.intValue();
                }else{
                    consume=consume+rentMoneyFen02.intValue();
                }
                logger.error("consume3:"+consume);
                refund=payAmountReal.intValue()-consume;
                logger.error("refund:"+refund);
                amount = consume;
            }
            xwPurchaseOrder.setUpdatedTime(endDate);
            xwPurchaseOrder.setFinishState("Y");
            xwPurchaseOrder.setRefundAmount(new BigDecimal(""+refund));
            xwPurchaseOrder.setRefundState("2");
            xwPurchaseOrder.setRentEndTime(endDate);
            xwPurchaseOrderMapper.updateXwPurchaseOrder(xwPurchaseOrder);
            if("2".equals(xwPurchaseOrder.getPayType())) {
                paymentRefundServiceImpl.createRefundOrder(xwPurchaseOrder.getOutTradeNo(),
                        payAmountReal.intValue(),refund);
            }
        }
        if ("1".equals(xwPurchaseOrder.getPayType())) {
            if (isCancel) {
                // 小于十分钟内变更为取消订单
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> rootNode = new HashMap<>();
                HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/payscore/serviceorder/" + xwPurchaseOrder.getOutTradeNo() + "/cancel");
                httpPost.addHeader("Accept", "application/json");
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                rootNode.put("appid", weChatConfig.getAppid());
                rootNode.put("service_id", weChatConfig.getServiceId());
                rootNode.put("reason", "取消订单");
                String body = objectMapper.writeValueAsString(rootNode);
                httpPost.setEntity(new StringEntity(body, "UTF-8"));
                logger.info("调用微信支付分取消订单接口:{}", body);
                CloseableHttpResponse response = httpClient.execute(httpPost);
                String bodyAsString = EntityUtils.toString(response.getEntity());
                logger.info("调用微信支付分取消订单接口返回:{}", bodyAsString);
                JsonNode jsonNode = objectMapper.readTree(bodyAsString);
                JsonNode orderId = jsonNode.get("order_id");
                if (orderId == null) {
                    throw new RuntimeException("取消支付订单错误.");
                }
            } else {
                // 微信支付分
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> rootNode = new HashMap<>();
                rootNode.put("appid", weChatConfig.getAppid());
                rootNode.put("service_id", weChatConfig.getServiceId());
                SysConfig sysConfig=sysConfigMapper.checkConfigKeyUniqueNew("xw_charging_details");
                String xw_charging_details  = sysConfig.getConfigName();
                List<Map<String, Object>> list = new ArrayList<>();
                Map<String, Object> data = new HashMap<>();
                data.put("name", "VR眼镜租赁费用");
//                data.put("amount", amount);
                data.put("description", xw_charging_details);
                list.add(data);
                rootNode.put("post_payments", list);
                Map<String, Object> timeData = new HashMap<>();
                timeData.put("end_time", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
                rootNode.put("time_range", timeData);
                rootNode.put("total_amount", amount);
                HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/payscore/serviceorder/" + xwPurchaseOrder.getOutTradeNo() + "/complete");
                httpPost.addHeader("Accept", "application/json");
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                String body = objectMapper.writeValueAsString(rootNode);
                httpPost.setEntity(new StringEntity(body, "UTF-8"));
                logger.info("调用微信支付分完成订单接口:{}", body);
                CloseableHttpResponse response = httpClient.execute(httpPost);
                String bodyAsString = EntityUtils.toString(response.getEntity());
                logger.info("调用微信支付分完成订单接口返回:{}", bodyAsString);
                JsonNode jsonNode = objectMapper.readTree(bodyAsString);
                JsonNode stateNode = jsonNode.get("state");
                if (stateNode == null) {
                    throw new RuntimeException("完结支付订单错误.");
                }
            }
        }
        return 3;
    }



    public List<LocalDate> getDateList(Date startDate,Date endDate) {

        // 将java.util.Date转换为java.time.LocalDate
        LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        // 创建日期范围的列表
        List<LocalDate> dateRange = new ArrayList<>();

        // 循环迭代两个日期之间的每个日期
        LocalDate currentDate = startLocalDate;
        while (currentDate.isBefore(endLocalDate) || currentDate.isEqual(endLocalDate)) {
            dateRange.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }
        // 输出每个日期
        for (LocalDate date : dateRange) {
            System.out.println(date.toString());
        }
        return dateRange;
    }
    public List<XwPurchaseOrder> getEnduserOrders(String openId){
        return xwPurchaseOrderMapper.getEnduserOrdersByOpenId(openId);
    }
    public List<XwPurchaseOrder> getAgentOrders(String openId){
        return xwPurchaseOrderMapper.getAgentOrdersByOpenId(openId);
    }

    /*
    每笔购买订单的分账处理
     */
    @Transactional
    public void dealBuyDivideOrder(XwPurchaseOrder xwPurchaseOrder){
        String deviceSn= xwPurchaseOrder.getDeviceSn();
        String outTradeNo=xwPurchaseOrder.getOutTradeNo();
        String transactionId=xwPurchaseOrder.getPrepayId();
        BigDecimal payAmountReal=xwPurchaseOrder.getPayAmountReal();
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        String agentOpenId=xwDevice.getAgentOpenId();
        String enduserOpenId=xwDevice.getEnduserOpenId();
        XwAgent xwAgent=xwAgentMapper.selectXwAgentByOpenId(agentOpenId);
        XwEnduser xwEnduser=xwEnduserMapper.selectXwEnduserByOpenId(enduserOpenId);
        JSONArray jsonArray=new JSONArray();
        if(xwAgent==null) {//代理商为空就没法分账
            return;
        }
        //代理商处理
        if(xwAgent.getFreezeState()==null||!xwAgent.getFreezeState().equals("Y")){//代理没有冻结
            JSONObject jsonObject=new JSONObject();
            BigDecimal percent=xwAgent.getAgentPercent();
            BigDecimal getMoney=payAmountReal.multiply(percent).divide(new BigDecimal("100"));
            jsonObject.put("payAmountReal",payAmountReal);
            jsonObject.put("openId",agentOpenId);
            jsonObject.put("userType","1");
            jsonObject.put("cashoutType",xwAgent.getCashoutType());
            jsonObject.put("percent",percent);
            jsonObject.put("getMoney",getMoney.intValue());
            if(xwAgent.getCashoutType().equals("1")){//零钱提现
                jsonObject.put("account",agentOpenId);
            }else{//商户号提现
                jsonObject.put("account",xwAgent.getAgentMerchantCode());
                jsonObject.put("accountName",xwAgent.getAgentMerchantName());
            }
            jsonArray.add(jsonObject);
        }
        //终端处理
        if(xwEnduser!=null&&(xwEnduser.getFreezeState()==null||!xwEnduser.getFreezeState().equals("Y"))){//终端没有被冻结
            JSONObject jsonObject=new JSONObject();
            BigDecimal percent=xwAgent.getTerminalPercent();
            BigDecimal getMoney=payAmountReal.multiply(percent).divide(new BigDecimal("100"));
            jsonObject.put("payAmountReal",payAmountReal);
            jsonObject.put("openId",enduserOpenId);
            jsonObject.put("userType","2");
            jsonObject.put("cashoutType",xwEnduser.getCashoutType());
            jsonObject.put("percent",percent);
            jsonObject.put("getMoney",getMoney.intValue());
            if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                jsonObject.put("account",enduserOpenId);
            }else{//商户号提现
                jsonObject.put("account",xwEnduser.getEnduserMerchantCode());
                jsonObject.put("accountName",xwEnduser.getEnduserMerchantName());
            }
            jsonArray.add(jsonObject);

            //业务1处理
            String enduserBusiness01=xwEnduser.getEnduserBusiness01();
            BigDecimal businessPercent01=xwEnduser.getBusinessPercent01();
            XwEnduser xwEnduser01=xwEnduserMapper.selectXwEnduserByOpenId(enduserBusiness01);
            if(xwEnduser01!=null&&(xwEnduser01.getFreezeState()==null||!xwEnduser01.getFreezeState().equals("Y"))){//终端没有被冻结
                BigDecimal getMoney01=payAmountReal.multiply(businessPercent01).divide(new BigDecimal("100"));
                JSONObject jsonObject01=new JSONObject();
                jsonObject.put("payAmountReal",payAmountReal);
                jsonObject01.put("openId",enduserBusiness01);
                jsonObject01.put("userType","3");
                jsonObject01.put("cashoutType",xwEnduser01.getCashoutType());
                jsonObject01.put("percent",businessPercent01);
                jsonObject01.put("getMoney",getMoney01.intValue());
                if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                    jsonObject01.put("account",enduserBusiness01);
                }else{//商户号提现
                    jsonObject01.put("account",xwEnduser01.getEnduserMerchantCode());
                    jsonObject01.put("accountName",xwEnduser01.getEnduserMerchantName());
                }
                jsonArray.add(jsonObject01);
            }
            //业务2处理
            String enduserBusiness02=xwEnduser.getEnduserBusiness02();
            BigDecimal businessPercent02=xwEnduser.getBusinessPercent02();
            XwEnduser xwEnduser02=xwEnduserMapper.selectXwEnduserByOpenId(enduserBusiness02);
            if(xwEnduser02!=null&&(xwEnduser02.getFreezeState()==null||!xwEnduser02.getFreezeState().equals("Y"))){//终端没有被冻结
                BigDecimal getMoney02=payAmountReal.multiply(businessPercent02).divide(new BigDecimal("100"));
                JSONObject jsonObject02=new JSONObject();
                jsonObject.put("payAmountReal",payAmountReal);
                jsonObject02.put("openId",enduserBusiness02);
                jsonObject02.put("userType","3");
                jsonObject02.put("cashoutType",xwEnduser02.getCashoutType());
                jsonObject02.put("percent",businessPercent02);
                jsonObject02.put("getMoney",getMoney02.intValue());
                if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                    jsonObject02.put("account",enduserBusiness02);
                }else{//商户号提现
                    jsonObject02.put("account",xwEnduser02.getEnduserMerchantCode());
                    jsonObject02.put("accountName",xwEnduser02.getEnduserMerchantName());
                }
                jsonArray.add(jsonObject02);
            }
        }
        logger.error("分账人信息：");
        logger.error(jsonArray.toString());
        if(jsonArray.size()<=0) {return;}
        //添加分账人和检查重复处理
        for(int i=0;i<jsonArray.size();i++){
            String cashoutType=jsonArray.getJSONObject(i).getString("cashoutType");
            String account=jsonArray.getJSONObject(i).getString("account");
            if(cashoutType.equals("1")){
                paymentDivideServiceImpl.addDividUser(account);
            }
        }

        //发起分账
        JSONArray jsonArrayNew=new JSONArray();
        for(int i=0;i<jsonArray.size();i++){
            boolean flag=true;
            for(int j=0;j<jsonArrayNew.size();j++){
                JSONObject jsonObject01=jsonArrayNew.getJSONObject(j);
                JSONObject jsonObject02=jsonArray.getJSONObject(i);
                String account01=jsonObject01.getString("account");
                String account02=jsonObject02.getString("account");
                if(account01.equals(account02)){
                    flag=false;
                    BigDecimal percent01=jsonObject01.getBigDecimal("percent");
                    BigDecimal percent02=jsonObject02.getBigDecimal("percent");
                    int getMoney01=jsonObject01.getIntValue("getMoney");
                    int getMoney02=jsonObject02.getIntValue("getMoney");
                    jsonObject01.put("percent",percent01.add(percent02));
                    jsonObject01.put("getMoney",(getMoney01+getMoney02));
                    jsonArrayNew.remove(j);
                    jsonArrayNew.add(jsonObject01);
                    break;
                }
            }
            if(flag){
                jsonArrayNew.add(jsonArray.getJSONObject(i));
            }

        }
        String description="洗衣球购买分账";
        logger.error("合并分账人信息：");
        logger.error(jsonArrayNew.toString());
        //{"order_id":"30000802872024010459101263853","out_order_no":"17036705601081923561","receivers":[{"account":"ofMKV6z5NOOQ14BBIZYwQdJofiWg","amount":6,"create_time":"2024-01-04T22:38:05+08:00","description":"洗衣球购买分账","detail_id":"36000802872024010484869484470","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"PERSONAL_OPENID"},{"account":"ofMKV63X-t1OB5CqAsMq9qJxTNcA","amount":3,"create_time":"2024-01-04T22:38:05+08:00","description":"洗衣球购买分账","detail_id":"36000802872024010484869484471","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"PERSONAL_OPENID"},{"account":"1657501348","amount":51,"create_time":"2024-01-04T22:38:05+08:00","description":"解冻给分账方","detail_id":"36000802872024010484869484472","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"MERCHANT_ID"}],"state":"PROCESSING","transaction_id":"4200002089202401046451680364"}
        String bodyAsString=paymentDivideServiceImpl.createDivideOrder(outTradeNo,transactionId,jsonArrayNew,description);
        String orderId=JSONObject.parseObject(bodyAsString).getString("order_id");
        logger.error("orderId："+orderId);
        //分账完成后的处理
        if(orderId!=null){
            xwPurchaseOrder.setDivideOrder(orderId);
            xwPurchaseOrder.setDivideState("3");
            xwPurchaseOrderMapper.updateXwPurchaseOrder(xwPurchaseOrder);
            for(int i=0;i<jsonArrayNew.size();i++){
                    JSONObject jsonObject=jsonArrayNew.getJSONObject(i);
                    XwDivideAccounts xwDivideAccounts=new XwDivideAccounts();
                    xwDivideAccounts.setDivideTotal(payAmountReal);
                    xwDivideAccounts.setDivideAmount(new BigDecimal(jsonObject.getString("getMoney")));
                    xwDivideAccounts.setOrderPercentage(jsonObject.getString("percent"));
                    xwDivideAccounts.setDivideAccount(jsonObject.getString("account"));
                    xwDivideAccounts.setCashoutType(jsonObject.getString("cashoutType"));
                    xwDivideAccounts.setAccountName(jsonObject.getString("accountName"));
                    xwDivideAccounts.setOpenId(jsonObject.getString("openId"));
                    xwDivideAccounts.setUserType(jsonObject.getString("userType"));
                    xwDivideAccounts.setDivideDesc(jsonObject.getString("divideDesc"));
                    xwDivideAccounts.setOutTradeNo(outTradeNo);
                    xwDivideAccounts.setDivideState("Y");
                    xwDivideAccountsMapper.insertXwDivideAccounts(xwDivideAccounts);
            }

        }

    }

    /*
    每笔购买订单的分账处理
     */
    @Transactional
    public void dealRentDivideOrder(XwPurchaseOrder xwPurchaseOrder){
        String deviceSn= xwPurchaseOrder.getDeviceSn();
        String outTradeNo=xwPurchaseOrder.getOutTradeNo();
        String transactionId=xwPurchaseOrder.getPrepayId();
        BigDecimal num01=xwPurchaseOrder.getPayAmountReal();//付款总额
        BigDecimal num02=xwPurchaseOrder.getRefundAmountReal();//退款总额
        int result=num01.compareTo(num02);
        if(result==0){//全额退款不分账
            return;
        }
        if(num02.compareTo(new BigDecimal("0"))==0){//超时订单不分账
            return;
        }
        BigDecimal payAmountReal=num01.subtract(num02);//收款总额
        XwDevice xwDevice=xwDeviceMapper.selectXwDeviceByDeviceSn(deviceSn);
        String agentOpenId=xwDevice.getAgentOpenId();
        String enduserOpenId=xwDevice.getEnduserOpenId();
        XwAgent xwAgent=xwAgentMapper.selectXwAgentByOpenId(agentOpenId);
        XwEnduser xwEnduser=xwEnduserMapper.selectXwEnduserByOpenId(enduserOpenId);
        JSONArray jsonArray=new JSONArray();
        if(xwAgent==null) {//代理商为空就没法分账
            return;
        }
        //代理商处理
        if(xwAgent.getFreezeState()==null||!xwAgent.getFreezeState().equals("Y")){//代理没有冻结
            JSONObject jsonObject=new JSONObject();
            BigDecimal percent=xwAgent.getAgentPercent();
            BigDecimal getMoney=payAmountReal.multiply(percent).divide(new BigDecimal("100"));
            jsonObject.put("payAmountReal",payAmountReal);
            jsonObject.put("openId",agentOpenId);
            jsonObject.put("userType","1");
            jsonObject.put("cashoutType",xwAgent.getCashoutType());
            jsonObject.put("percent",percent);
            jsonObject.put("getMoney",getMoney.intValue());
            if(xwAgent.getCashoutType().equals("1")){//零钱提现
                jsonObject.put("account",agentOpenId);
            }else{//商户号提现
                jsonObject.put("account",xwAgent.getAgentMerchantCode());
                jsonObject.put("accountName",xwAgent.getAgentMerchantName());
            }
            jsonArray.add(jsonObject);
        }
        //终端处理
        if(xwEnduser!=null&&(xwEnduser.getFreezeState()==null||!xwEnduser.getFreezeState().equals("Y"))){//终端没有被冻结
            JSONObject jsonObject=new JSONObject();
            BigDecimal percent=xwAgent.getTerminalPercent();
            BigDecimal getMoney=payAmountReal.multiply(percent).divide(new BigDecimal("100"));
            jsonObject.put("payAmountReal",payAmountReal);
            jsonObject.put("openId",enduserOpenId);
            jsonObject.put("userType","2");
            jsonObject.put("cashoutType",xwEnduser.getCashoutType());
            jsonObject.put("percent",percent);
            jsonObject.put("getMoney",getMoney.intValue());
            if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                jsonObject.put("account",enduserOpenId);
            }else{//商户号提现
                jsonObject.put("account",xwEnduser.getEnduserMerchantCode());
                jsonObject.put("accountName",xwEnduser.getEnduserMerchantName());
            }
            jsonArray.add(jsonObject);

            //业务1处理
            String enduserBusiness01=xwEnduser.getEnduserBusiness01();
            BigDecimal businessPercent01=xwEnduser.getBusinessPercent01();
            XwEnduser xwEnduser01=xwEnduserMapper.selectXwEnduserByOpenId(enduserBusiness01);
            if(xwEnduser01!=null&&(xwEnduser01.getFreezeState()==null||!xwEnduser01.getFreezeState().equals("Y"))){//终端没有被冻结
                BigDecimal getMoney01=payAmountReal.multiply(businessPercent01).divide(new BigDecimal("100"));
                JSONObject jsonObject01=new JSONObject();
                jsonObject.put("payAmountReal",payAmountReal);
                jsonObject01.put("openId",enduserBusiness01);
                jsonObject01.put("userType","3");
                jsonObject01.put("cashoutType",xwEnduser01.getCashoutType());
                jsonObject01.put("percent",businessPercent01);
                jsonObject01.put("getMoney",getMoney01.intValue());
                if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                    jsonObject01.put("account",enduserBusiness01);
                }else{//商户号提现
                    jsonObject01.put("account",xwEnduser01.getEnduserMerchantCode());
                    jsonObject01.put("accountName",xwEnduser01.getEnduserMerchantName());
                }
                jsonArray.add(jsonObject01);
            }
            //业务2处理
            String enduserBusiness02=xwEnduser.getEnduserBusiness02();
            BigDecimal businessPercent02=xwEnduser.getBusinessPercent02();
            XwEnduser xwEnduser02=xwEnduserMapper.selectXwEnduserByOpenId(enduserBusiness02);
            logger.error("getFreezeState："+xwEnduser02.getFreezeState());
            if(xwEnduser02!=null&&(xwEnduser02.getFreezeState()==null||!xwEnduser02.getFreezeState().equals("Y"))){//终端没有被冻结
                BigDecimal getMoney02=payAmountReal.multiply(businessPercent02).divide(new BigDecimal("100"));
                JSONObject jsonObject02=new JSONObject();
                jsonObject.put("payAmountReal",payAmountReal);
                jsonObject02.put("openId",enduserBusiness02);
                jsonObject02.put("userType","3");
                jsonObject02.put("cashoutType",xwEnduser02.getCashoutType());
                jsonObject02.put("percent",businessPercent02);
                jsonObject02.put("getMoney",getMoney02.intValue());
                if(xwEnduser.getCashoutType().equals("1")){//零钱提现
                    jsonObject02.put("account",enduserBusiness02);
                }else{//商户号提现
                    jsonObject02.put("account",xwEnduser02.getEnduserMerchantCode());
                    jsonObject02.put("accountName",xwEnduser02.getEnduserMerchantName());
                }
                jsonArray.add(jsonObject02);
            }
        }
        logger.error("分账人信息：");
        logger.error(jsonArray.toString());
        if(jsonArray.size()<=0) {return;}
        //添加分账人和检查重复处理
        for(int i=0;i<jsonArray.size();i++){
            String cashoutType=jsonArray.getJSONObject(i).getString("cashoutType");
            String account=jsonArray.getJSONObject(i).getString("account");
            if(cashoutType.equals("1")){
                paymentDivideServiceImpl.addDividUser(account);
            }
        }

        //发起分账
        JSONArray jsonArrayNew=new JSONArray();
        for(int i=0;i<jsonArray.size();i++){
            boolean flag=true;
            for(int j=0;j<jsonArrayNew.size();j++){
                JSONObject jsonObject01=jsonArrayNew.getJSONObject(j);
                JSONObject jsonObject02=jsonArray.getJSONObject(i);
                String account01=jsonObject01.getString("account");
                String account02=jsonObject02.getString("account");
                if(account01.equals(account02)){
                    flag=false;
                    BigDecimal percent01=jsonObject01.getBigDecimal("percent");
                    BigDecimal percent02=jsonObject02.getBigDecimal("percent");
                    int getMoney01=jsonObject01.getIntValue("getMoney");
                    int getMoney02=jsonObject02.getIntValue("getMoney");
                    jsonObject01.put("percent",percent01.add(percent02));
                    jsonObject01.put("getMoney",(getMoney01+getMoney02));
                    jsonArrayNew.remove(j);
                    jsonArrayNew.add(jsonObject01);
                    break;
                }
            }
            if(flag){
                jsonArrayNew.add(jsonArray.getJSONObject(i));
            }

        }
        String description="洗衣球购买分账";
        logger.error("合并分账人信息：");
        logger.error(jsonArrayNew.toString());
        //{"order_id":"30000802872024010459101263853","out_order_no":"17036705601081923561","receivers":[{"account":"ofMKV6z5NOOQ14BBIZYwQdJofiWg","amount":6,"create_time":"2024-01-04T22:38:05+08:00","description":"洗衣球购买分账","detail_id":"36000802872024010484869484470","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"PERSONAL_OPENID"},{"account":"ofMKV63X-t1OB5CqAsMq9qJxTNcA","amount":3,"create_time":"2024-01-04T22:38:05+08:00","description":"洗衣球购买分账","detail_id":"36000802872024010484869484471","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"PERSONAL_OPENID"},{"account":"1657501348","amount":51,"create_time":"2024-01-04T22:38:05+08:00","description":"解冻给分账方","detail_id":"36000802872024010484869484472","finish_time":"1970-01-01T08:00:00+08:00","result":"PENDING","type":"MERCHANT_ID"}],"state":"PROCESSING","transaction_id":"4200002089202401046451680364"}
        String bodyAsString=paymentDivideServiceImpl.createDivideOrder(outTradeNo,transactionId,jsonArrayNew,description);
        String orderId=JSONObject.parseObject(bodyAsString).getString("order_id");
        logger.error("orderId："+orderId);
        //分账完成后的处理
        if(orderId!=null){
            xwPurchaseOrder.setDivideOrder(orderId);
            xwPurchaseOrder.setDivideState("3");
            xwPurchaseOrderMapper.updateXwPurchaseOrder(xwPurchaseOrder);
            for(int i=0;i<jsonArrayNew.size();i++){
                JSONObject jsonObject=jsonArrayNew.getJSONObject(i);
                XwDivideAccounts xwDivideAccounts=new XwDivideAccounts();
                xwDivideAccounts.setDivideTotal(payAmountReal);
                xwDivideAccounts.setDivideAmount(new BigDecimal(jsonObject.getString("getMoney")));
                xwDivideAccounts.setOrderPercentage(jsonObject.getString("percent"));
                xwDivideAccounts.setDivideAccount(jsonObject.getString("account"));
                xwDivideAccounts.setCashoutType(jsonObject.getString("cashoutType"));
                xwDivideAccounts.setAccountName(jsonObject.getString("accountName"));
                xwDivideAccounts.setOpenId(jsonObject.getString("openId"));
                xwDivideAccounts.setUserType(jsonObject.getString("userType"));
                xwDivideAccounts.setDivideDesc(jsonObject.getString("divideDesc"));
                xwDivideAccounts.setOutTradeNo(outTradeNo);
                xwDivideAccounts.setDivideState("Y");
                xwDivideAccountsMapper.insertXwDivideAccounts(xwDivideAccounts);
            }

        }

    }

    public static void main(String[] args) {
        BigDecimal num01=new BigDecimal("0");//付款总额
        BigDecimal num02=new BigDecimal("0.00");//付款总额;//退款总额
        System.out.println(num01.compareTo(num02));
    }
}
